import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Between, Not, Repository, In } from 'typeorm';
import { OrderShopEntity } from '../entity/shop';
import { OrderCityEntity } from '../entity/city';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { AppointmentLimitEntity } from '../../appointment/entity/limit';
import { OrderOrderEntity } from '../entity/order';
import moment = require('moment');
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { AgentRelationService } from '../../agent/service/agent';



/**
 * 订单模块-店铺信息Service
 */
@Provide()
export class OrderShopService extends BaseService {
  @InjectEntityModel(OrderShopEntity)
  orderShopEntity: Repository<OrderShopEntity>;

  @InjectEntityModel(OrderCityEntity)
  orderCityEntity: Repository<OrderCityEntity>;

  @InjectEntityModel(AppointmentInfoEntity)
  appointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(AppointmentLimitEntity)
  appointmentLimitEntity: Repository<AppointmentLimitEntity>;

  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @Inject()
  agentRelationService: AgentRelationService;

  @Inject()
  ctx;

  // 获取店铺列表
  async getShopList(cityName: string) {
    const city = await this.orderCityEntity.findOne({
      where: {
        cityName: cityName
      }
    });
    if (!city) {
      throw new Error('该城市没有店铺哦');
    }
    return this.orderShopEntity.find({
      where: {
        cityId: city.id,
        id: Not(In([36, 31]))
      }
    });
  }

  // 获取单个店铺信息
  async getShopInfo(shopId: number) {
    return this.orderShopEntity.findOne({
      where: {
        id: shopId
      }
    });
  }

  // 根据店铺ID和日期获取最近7天的预约情况
  async getAppointmentInfo(shopId: number, date: string) {
    // 计算最近7天的开始和结束日期
    const startDate = moment(date).format('YYYY-MM-DD');
    // 查询最近7天的预约信息
    const appointments = await this.appointmentInfoEntity.find({  
      where: {
        shopId: shopId,
        appointmentTime: Between(new Date(startDate + ' 00:00:00'), new Date(startDate + ' 23:59:59')),
        appointmentStatus: Not(In([2, 4])),
      }
    });
    // 处理预约信息，显示每天的可以预约时间和时间是否被预约，时间段是09:00-18:00
    // 需要将日期和每天的时间段都分别初始化，每个时间段有预约人数，是否可预约，预约状态的显示
    // 每小时间隔一个 时间段，每个时间段是60分钟
    const timeSlots = ['09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'];
    const appointmentInfo = [];
    // 查看是否有限制
    const limit = await this.appointmentLimitEntity.findOne({
      where: {
        shopId: shopId,
        week: moment(startDate).day(),
        type: 0
      }
    });
    // console.log(shopId, moment(startDate).day(), limit);
    for (let i = 0; i < 1; i++) {
      const date = moment(startDate).add(i, 'days').format('YYYY-MM-DD');
      timeSlots.forEach(timeSlot => {
        // 查看时段是否存在
        const time = limit?.time?.split(',');
        let canAppoint = true;
        if (time?.includes(timeSlot)) {
          canAppoint = false;
        }

        appointmentInfo.push({
          date: date,
          timeSlot: timeSlot,
          canAppoint: canAppoint,
          appointed: false,
          showText: canAppoint ? '可预约' : '已预约',
          timeText: `${timeSlot}~${moment(timeSlot, 'HH:mm').add(60, 'minutes').format('HH:mm')}`,
          status: canAppoint ? 1 : 0,
        });
      });
    }
    // console.log(appointmentInfo);
    // 遍历预约信息，更新预约状态
    appointments.forEach(appointment => {
      const date = moment(appointment.appointmentTime).format('YYYY-MM-DD');
      const timeSlot = moment(appointment.appointmentTime).format('HH:mm');
      const appoint = appointmentInfo.find(item => item.date === date && item.timeSlot === timeSlot);
      // console.log(date, timeSlot, appoint);
      if (appoint) {
        appoint.canAppoint = false;
        appoint.appointed = true;
        appoint.showText = '已预约';
        appoint.status = 0;
      }
    });
    return {
      appointmentInfo,
      timeSlots,
    }
  }

  // 根据店铺获取开放的期数
  async getOpenPeriods() {
    // const shop = await this.orderShopEntity.findOne({
    //   where: {
    //     id: shopId
    //   }
    // });
    // if (!shop) {
    //   throw new Error('该店铺不存在');
    // }
    // 计算当前日期的最近两周
    const currentDate = moment();
    const startDate = currentDate.format('YYYY-MM-DD');
    const endDate = currentDate.add(14, 'days').format('YYYY-MM-DD');
    // 初始化期数数据结构，根据开始和结束日期，计算有多少期，完整的周一到周日算一期
    const periods = [];
    const start = moment(startDate).startOf('week').add(1, 'day'); // 为startDate的周一
    const end = moment(endDate).endOf('week').add(1, 'day'); // 为endDate的周日
    const diff = end.diff(start, 'weeks');
    console.log(start, end, diff)
    // 根据开始日期计算现在是第几期，每一周是一期
    const peroidEndDate = moment('2025-08-03');
    // 初始化到第二十的数组
    const chineseNumbers = ['', '第一', '第二', '第三', '第四', '第五', '第六', '第七', '第八', '第九', '第十', '第十一', '第十二', '第十三', '第十四', '第十五', '第十六', '第十七', '第十八', '第十九', '第二十'];
    const chinesePeroid = [];
    for (let i = 1; i <= 20; i++) {
      const period = i == 1 ? peroidEndDate.format('YYYY-MM-DD') : peroidEndDate.add(7, 'days').format('YYYY-MM-DD');
      chinesePeroid.push({
        period: chineseNumbers[i] + '期',
        endDate: period,
        endDateText: period,
      });
    }
    const preWeek = 1;
    // 在数组前面添加一期已约满
    periods.push({
      endDate: start.subtract(7 * preWeek + 1, 'day').format('YYYY-MM-DD'),
      period: chinesePeroid.find(item => item.endDate === start.format('YYYY-MM-DD'))?.period || '-', // 在chinesePeroid找到endDate一致的期数
      endDateText: start.format('MM月DD日'),
      startDate: start.subtract(6, 'day').format('YYYY-MM-DD'),
      startDateText: start.format('MM月DD日'),
      process: '已约满',
      status: 0,
    });
    for (let i = 0; i < diff + preWeek; i++) {
      periods.push({
        startDate: i == 0 ? start.add(7, 'days').format('YYYY-MM-DD') : start.add(1, 'days').format('YYYY-MM-DD'),
        startDateText: start.format('MM月DD日'),
        endDate: start.add(6, 'days').format('YYYY-MM-DD'),
        period: chinesePeroid.find(item => item.endDate === start.format('YYYY-MM-DD'))?.period || '-',
        endDateText: start.format('MM月DD日'),
        process: i < preWeek + 1 ? '已约满' : '进行中',
        status: i < preWeek + 1 ? 0 : 1,
      });
    }
    
    // 在数组最后添加一期未开始
    periods.push({
      startDate: start.add(1, 'days').format('YYYY-MM-DD'),
      startDateText: start.format('MM月DD日'),
      endDate: start.add(6, 'days').format('YYYY-MM-DD'),
      period: chinesePeroid.find(item => item.endDate === start.format('YYYY-MM-DD'))?.period || '-',
      endDateText: start.format('MM月DD日'),
      process: '未开始',
      status: 2,
    });
    // 在数组最后添加一期未开始
    periods.push({
      startDate: start.add(1, 'days').format('YYYY-MM-DD'),
      startDateText: start.format('MM月DD日'),
      endDate: start.add(6, 'days').format('YYYY-MM-DD'),
      period: chinesePeroid.find(item => item.endDate === start.format('YYYY-MM-DD'))?.period || '-',
      endDateText: start.format('MM月DD日'),
      process: '未开始',
      status: 2,
    });
    
    return periods;
  }

  /**
   * 店铺选择列表
   */
  async getSelectList() {
    const shops = await this.orderShopEntity.find({
    });
    return shops.map(user => ({
      label: user.name,
      value: user.id
    }));
  }

  /**
   * 店铺选择店铺列表
   */
  async getShopSelectList(shopId) {
    const shops = await this.orderShopEntity.find({
      where: {
        id: shopId
      }
    });
    return shops.map(user => ({
      label: user.name,
      value: user.id
    }));
  }

  // 根据代理商ID选择店铺
  async getShopSelectListByAgentId(agentId: number) {
    const shopIds = await this.agentRelationService.getAgentShopIdsByAgentId(agentId);
    const shops = await this.orderShopEntity.find({
      where: {
        id: In(shopIds)
      }
    });
    return shops.map(user => ({
      label: user.name,
      value: user.id
    }));
  }

  


  // 根据订单ID获取店铺信息
  async getShopInfoByOrderId(orderId: number) {
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: orderId
      }
    });
    if (!order) {
      throw new Error('订单不存在');
    }
    const shop = await this.orderShopEntity.findOne({
      where: {
        id: order.shopId
      }
    });
    if (!shop) {
      throw new Error('店铺不存在');
    }
    // 拼上城市名称
    const city = await this.orderCityEntity.findOne({
      where: {
        id: shop.cityId
      }
    });
    if (!city) {
      throw new Error('城市不存在');
    }
    const result = {
      ...shop,
      cityName: city.cityName,
    }

    return result;
  }

  // 根据用户id获取商铺信息
  async getShopInfoByUserId(body) {
    console.log('this.ctx.admin', this.ctx.admin);
    const users = await this.baseSysUserEntity.findOne({
      where: {
        id: this.ctx.admin.userId,
      },
    });
    const shop = await this.orderShopEntity.findOne({
      where: {
        id: users.shopId,
      },
    });
    return shop;
  }
}
